package net.wanji.redistooracle.service.impl;

import net.wanji.redistooracle.mapper.BusiAttrDao;
import net.wanji.redistooracle.model.BusiAttrModel;
import net.wanji.redistooracle.service.DataMigrationService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Set;

/**
 * @author weixiaochun
 */
@Service
public class DataMigrationServiceImpl implements DataMigrationService {

    private final Logger log = LoggerFactory.getLogger(DataMigrationServiceImpl.class);

    @Resource
    private JedisPool jedisPool;

    private static final Integer MAX_SIZE = 13000000;

    @Autowired
    private BusiAttrDao busiAttrDao;


    @Override
    public int redisToOracle(String prefix, String suffix) {
        Jedis jedis = jedisPool.getResource();
        String pattern = "*";
        if(StringUtils.isNotBlank(prefix)){
            pattern += prefix;
        }
        if(StringUtils.isNoneBlank(suffix)){
            pattern = pattern + suffix;
        }

        Long start = System.currentTimeMillis();
        Set<String> keys = jedis.keys(pattern);
//            for (int i = 0; i < MAX_SIZE; i++) {
//                jedis.set("s" + i + "pms", String.valueOf(i));
//            }

        log.info("总耗时：{} ms, 读取数据{}条", System.currentTimeMillis() - start, keys.size());
        int num = 0;
        start = System.currentTimeMillis();
        ArrayList<BusiAttrModel> list = new ArrayList<>(1000);
        for (String key : keys) {
            BusiAttrModel busiAttrModel = new BusiAttrModel();
            num++;
            String value = jedis.get(key);
            busiAttrModel.setDataKey(key);
            busiAttrModel.setDataValue(value);
            list.add(busiAttrModel);
            if(num == 1000){
//                    start = System.currentTimeMillis();
                busiAttrDao.batchInsert(list);
                list.clear();
                num = 0;
            }
        }
        log.info("添加到List总耗时：{} ms", System.currentTimeMillis() - start);
        return 0;
    }
}
